package com.shipwe.loans.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.os.Build
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import com.google.android.gms.auth.api.phone.SmsRetriever
import com.shipwe.loans.R
import com.shipwe.loans.databinding.ActivityCheckPhoneNumberBinding
import com.shipwe.loans.pro.ShipweActivity
import com.shipwe.loans.ui.presenter.CheckNumberPresenter
import com.shipwe.loans.ui.view.ICheckNumberView
import com.shipwe.loans.utils.dialog.CheckNumberBirthdayDialog
import com.shipwe.loans.utils.dialog.CheckNumberSendSuccessDialog
import com.shipwe.loans.utils.event.AppEventData
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.CustomProcessHelper
import com.shipwe.loans.utils.log.ShipweLogger
import com.shipwe.loans.utils.shared.ShipweSharedHelper
import com.shipwe.loans.utils.shared.ShipweSharedKey
import com.shipwe.loans.utils.sms.ShipweSMSBroadcastReceiver
import com.shipwe.loans.utils.thread.TimingThread
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/11 16:41
 * @Annotation：账号验证页面
 */
class ActivityCheckNumber: ShipweActivity(), ICheckNumberView,TimingThread.ITimingThreadListener, CoroutineScope by MainScope() {
    lateinit var binding: ActivityCheckPhoneNumberBinding
    var presenter: CheckNumberPresenter? = null
    private var sendSuccessDialog: CheckNumberSendSuccessDialog? = null
    private var smsBroadcastReceiver: ShipweSMSBroadcastReceiver? = null

    private val SMS_CONSENT_REQUEST = 200
    var eventRemark = ""

    private var timeThread: TimingThread? = null
    //等待时长
    private var countdown = 60

    //需要选择出生日期
    private var birthdayDialog: CheckNumberBirthdayDialog? = null
    companion object {
        private const val INTENT_KEY_PRODUCT = "product"
        private const val INTENT_KEY_TOKEN = "token"
        fun start(context: Context, pName: String, pToken: String) {
            val intent = Intent(context, ActivityCheckNumber::class.java)
            intent.putExtra(INTENT_KEY_PRODUCT, pName)
            intent.putExtra(INTENT_KEY_TOKEN, pToken)
            context.startActivity(intent)
        }
    }
    override fun getShipweRootView(): View? {
        binding = ActivityCheckPhoneNumberBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initShipweView() {
        rootViewBinding.rootLayout.setBackgroundResource(R.drawable.page_login_bg)
        setShipweTitleBarVisibility(View.VISIBLE)
        setShipweBackBtnVisibility(View.GONE)
        setShipweRightBtnRes(R.drawable.customer_black)
        setShipweTextTitle("")

        initCheckNumberRefreshView()
        showChcekPhoneNumberTypeView(false)

        SmsRetriever.getClient(this).startSmsUserConsent(null)
        registerSMSBroadcastReceiver()
    }

    override fun initShipweListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog(eventRemark,getProductName(),getProductToken())
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_CUSTOMER,eventRemark)
        }
        binding.checkNumberCode.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                binding.checkNumberContinue.isEnabled = presenter!!.getCheckNumberSelectType().isNotEmpty() && getCheckNumberCode().isNotEmpty()
            }
        })

        //SMS
        binding.smsLayout.setOnClickListener {
            presenter?.setCheckNumberType("SMS")
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_VERIFICATION_SMS)
        }

        //WhatsApp
        binding.whatsappLayout.setOnClickListener {
            presenter?.setCheckNumberType("WHATSAPP")
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_VERIFICATION_WHATSAPP)
        }

        binding.checkNumberGet.setOnClickListener {
            if (presenter!!.getCheckNumberSelectType().isEmpty()){
                return@setOnClickListener
            }
            presenter?.sendCheckNumberWhatsAppCodeAction()
        }

        binding.checkNumberContinue.setOnClickListener {
            if (getCheckPhoneNumber().isEmpty() || getCheckNumberCode().isEmpty()){
                binding.checkNumberContinue.isEnabled = false
                return@setOnClickListener
            }
            presenter?.onCheckNumberVerificationCodeAction()
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_VERIFICATION_CONTINUE)
        }
        binding.checkNumberEdit.setOnClickListener {
           showChcekPhoneNumberTypeView(true)
        }
        binding.checkNumberConfirm.setOnClickListener {
            if (getCheckPhoneNumber().isEmpty()){
                return@setOnClickListener
            }
            showChcekPhoneNumberTypeView(false)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initShipweData() {
        presenter = CheckNumberPresenter(this)
        val zoneCode = ShipweSharedHelper.getShipweSharedString(ShipweSharedKey.SHIPWE_TIMEZONE_CODE)
        val mobile = ShipweSharedHelper.getShipweSharedString(ShipweSharedKey.SHIPWE_MOBILE)
        binding.checkNumberZoneCode.text = "+$zoneCode"
        binding.phoneNumber.setText(mobile)

        binding.checkNumberGet.text = getString(R.string.click_get)
        binding.checkNumberGet.isEnabled = false
        binding.smsLayout.isEnabled = true
        binding.whatsappLayout.isEnabled = true

        binding.smsLayout.visibility = View.GONE
        binding.whatsappLayout.visibility = View.GONE
        if (CustomProcessHelper.isCheckSMS()){
            binding.smsLayout.visibility = View.VISIBLE
        }
        if (CustomProcessHelper.isCheckWhatsApp()){
            binding.whatsappLayout.visibility = View.VISIBLE
        }
        showDefaultCheckTypeView()
    }

    /**
     * 注册SMS广播接收
     */
    private fun registerSMSBroadcastReceiver(){
        // 2 register receiver
        val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION)
        smsBroadcastReceiver = ShipweSMSBroadcastReceiver {
            startActivityForResult(it, SMS_CONSENT_REQUEST)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13 及以上版本使用 receiverFlags 参数
            registerReceiver(
                smsBroadcastReceiver,
                intentFilter,
                SmsRetriever.SEND_PERMISSION,
                null,
                Context.RECEIVER_EXPORTED // 指定导出标志
            )
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Android 8.0 到 Android 12 版本使用带权限的 registerReceiver()
            registerReceiver(
                smsBroadcastReceiver,
                intentFilter,
                SmsRetriever.SEND_PERMISSION,
                null
            )
        } else {
            // Android 8.0 以下版本，只使用 receiver 和 intentFilter 参数
            registerReceiver(
                smsBroadcastReceiver,
                intentFilter
            )
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == SMS_CONSENT_REQUEST) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                // 读取短信内容
                val message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE)
                ShipweLogger.e("Sms content: $message")

                // 提取otp
                val code = extractFirstNumber(message)
                ShipweLogger.e("Sms code: $code")
                if (code != null){
                    binding.checkNumberCode.setText(code)
                }
            } else {
                // 用户不同意或没收到待
                ShipweLogger.e("User canceled or no message received")
            }
        }
    }

    /* 初始化刷新 */
    private fun initCheckNumberRefreshView() {
        //禁止加载
        binding.checkNumberRefreshView.setEnableLoadMore(false)
        binding.checkNumberRefreshView.setEnableAutoLoadMore(false)
        binding.checkNumberRefreshView.setOnRefreshListener {
            publishEventData(AppEventData(AppEventData.TYPE.SHIPWE_PROCESS_REFRESH))
        }
        binding.checkNumberRefreshView.setOnLoadMoreListener {
            binding.checkNumberRefreshView.finishLoadMore()
        }
    }

    /**
     * 获取查看的产品名称
     */
    override fun getProductName(): String {
        return intent.extras!!.getString(INTENT_KEY_PRODUCT).toString()
    }

    /**
     * 获取查看的产品Token
     */
    override fun getProductToken(): String {
        return intent.extras!!.getString(INTENT_KEY_TOKEN).toString()
    }

    /**
     * 获取手机号
     */
    override fun getCheckPhoneNumber(): String {
        return binding.phoneNumber.text.toString().trim()
    }

    /**
     * 获取验证码
     */
    override fun getCheckNumberCode(): String {
        return binding.checkNumberCode.text.toString().trim()
    }

    /**
     * 切换是否修改手机号View
     */
    private fun showChcekPhoneNumberTypeView(isEdit: Boolean){
        //是否允许修改手机号码
        if (!CustomProcessHelper.isMobileEditFlag()){
            binding.checkNumberLine.visibility = View.GONE
            binding.phoneNumber.isFocusable = false
            binding.phoneNumber.isFocusableInTouchMode = false
            binding.checkNumberEdit.visibility = View.GONE
            binding.checkNumberConfirm.visibility = View.GONE
            binding.phoneNumberViewGroup.setBackgroundColor(Color.parseColor("#00000000"))
            return
        }
        binding.checkNumberLine.visibility = View.VISIBLE
        when(isEdit){
            true -> {
                binding.checkNumberEdit.visibility = View.GONE
                binding.checkNumberConfirm.visibility = View.VISIBLE
                binding.phoneNumber.isFocusable = true
                binding.phoneNumber.isFocusableInTouchMode = true
                binding.phoneNumber.requestFocus()
                binding.phoneNumber.setSelection(binding.phoneNumber.text.toString().length)
                binding.phoneNumberViewGroup.setBackgroundResource(R.drawable.check_number_edit_bg)
            }
            else -> {
                binding.checkNumberEdit.visibility = View.VISIBLE
                binding.checkNumberConfirm.visibility = View.GONE
                binding.phoneNumber.isFocusable = false
                binding.phoneNumber.isFocusableInTouchMode = false
                binding.phoneNumberViewGroup.setBackgroundResource(R.drawable.check_number_default_bg)
            }
        }
    }

    /**
     * 设置默认选中校验类型
     */
    private fun showDefaultCheckTypeView(){
        //设置默认选中：有SMS就选中SMS，否则选中WHATSAPP
        if (CustomProcessHelper.isCheckSMS()){
            presenter?.setCheckNumberType("SMS",false)
        } else {
            presenter?.setCheckNumberType("WHATSAPP",false)
        }
    }

    /**
     * 切换校验类型
     */
    override fun showCheckNumberType(type: String) {
        binding.checkNumberGet.isEnabled = true

        binding.whatsappLayout.setLayoutBackground(Color.parseColor("#FFFFFFFF"))
        binding.whatsAppIcon.setImageResource(R.drawable.page_check_number_whatsapp_normal)
        binding.whatsAppTitle.setTextColor(Color.parseColor("#FFB8B5B4"))
        binding.whatsAppSelect.setImageResource(R.drawable.page_check_number_normal)

        binding.smsLayout.setLayoutBackground(Color.parseColor("#FFFFFFFF"))
        binding.smsIcon.setImageResource(R.drawable.page_check_number_sms_normal)
        binding.smsTitle.setTextColor(Color.parseColor("#FFB8B5B4"))
        binding.smsSelect.setImageResource(R.drawable.page_check_number_normal)
        when(type){
            "SMS" -> {
                binding.smsLayout.setLayoutBackground(Color.parseColor("#FF7543FF"))
                binding.smsIcon.setImageResource(R.drawable.page_check_number_sms_select)
                binding.smsTitle.setTextColor(Color.parseColor("#FFFFFFFF"))
                binding.smsSelect.setImageResource(R.drawable.page_check_number_select)
            }
            else -> {
                binding.whatsappLayout.setLayoutBackground(Color.parseColor("#FF7543FF"))
                binding.whatsAppIcon.setImageResource(R.drawable.page_check_number_whatsapp_select)
                binding.whatsAppTitle.setTextColor(Color.parseColor("#FFFFFFFF"))
                binding.whatsAppSelect.setImageResource(R.drawable.page_check_number_select)
            }
        }
        binding.checkNumberContinue.isEnabled = getCheckNumberCode().isNotEmpty()
    }

    /**
     * 验证码发送成功
     * 当为YES时可以跳过，直接调用流程接口，根据流程步骤whatsappFlag标识走
     */
    override fun showCheckNumberSendCodeSuccess(directLoginFlag: String) {
        dismissShipweLoading()
        when(directLoginFlag){
            "YES" -> {
                showCheckNumberSuccess()
            }
            else -> {
                startTimeThread()
            }
        }
    }

    /**
     * 需要选择出生日期
     */
    override fun showCheckNumberChooseBirthdayDialog() {
        if (birthdayDialog == null){
            birthdayDialog = CheckNumberBirthdayDialog(this)
            birthdayDialog?.setCheckNumberBirthdayCancelable(true)
            birthdayDialog?.setCheckNumberBirthdayCanceledOnTouchOutside(false)
            birthdayDialog?.setCheckNumberBirthdayClickCallback(object : CheckNumberBirthdayDialog.IDialogCallback{
                override fun onSubmitSelectBirthday(data: JSONObject) {
                    presenter?.onCheckNumberVerificationCodeAction(data.optString("subDate"))
                }
            })
        }
        birthdayDialog?.show()
    }


    /**
     * 校验成功
     */
    override fun showCheckNumberSuccess() {
        ShipweSharedHelper.putShipweSharedData(ShipweSharedKey.SHIPWE_MOBILE, getCheckPhoneNumber())
        publishEventData(AppEventData(AppEventData.TYPE.SHIPWE_PROCESS_REFRESH))
        finish()
    }

    /**
     * 发送成功提示
     */
    private fun showCheckNumberSendSuccessDialog(){
        if (sendSuccessDialog == null){
            sendSuccessDialog = CheckNumberSendSuccessDialog(this)
            sendSuccessDialog!!.setCancelable(true)
            sendSuccessDialog!!.setCanceledOnTouchOutside(false)
        }
        sendSuccessDialog!!.show()
        launch(Dispatchers.Main){
            delay(2000)
            sendSuccessDialog!!.dismiss()
        }
    }

    /**
     * 提取连续的数字
     */
    private fun extractFirstNumber(input: String?): String? {
        if(input.isNullOrBlank()) return ""

        val regex = "\\d+".toRegex()
        return regex.find(input)?.value
    }

    /**
     * 启动倒计时
     */
    @SuppressLint("SetTextI18n")
    private fun startTimeThread() {
        if (timeThread != null) {
            timeThread!!.stopThread()
        }
        showCheckNumberSendSuccessDialog()
        //随机 60秒 等待时长
        countdown = 59
        binding.checkNumberGet.text = "${countdown}s"
        binding.checkNumberGet.isEnabled = false
        binding.smsLayout.isEnabled = false
        binding.smsLayout.setClickable(false)
        binding.whatsappLayout.isEnabled = false
        binding.whatsappLayout.setClickable(false)
        if (timeThread == null) {
            timeThread = TimingThread()
            timeThread!!.setThreadDelayMillis(1000)
            timeThread!!.setLoadListener(this)
        }
        timeThread!!.startThread()
    }

    @SuppressLint("SetTextI18n")
    override fun onLoading() {
        if (countdown <= 0){
            countdown = 60
            timeThread!!.stopThread()
            binding.checkNumberGet.text = getString(R.string.click_get)
            binding.checkNumberGet.isEnabled = true
            binding.smsLayout.isEnabled = true
            binding.smsLayout.setClickable(true)
            binding.whatsappLayout.isEnabled = true
            binding.whatsappLayout.setClickable(true)
            return
        }
        countdown--
        binding.checkNumberGet.text = "${countdown}s"
    }

    override fun onShipwePublishEvent(event: AppEventData) {
        super.onShipwePublishEvent(event)
        when(event.eventType){
            AppEventData.TYPE.SHIPWE_PROCESS_REFRESHED -> {
                dismissShipweLoading()
                //需要校验 WhatsApp 或 SMS
                if (!CustomProcessHelper.isCheckWhatsApp() && !CustomProcessHelper.isCheckSMS()){
                    //校验成功
                    showCheckNumberSuccess()
                }
            }
            else -> {

            }
        }
    }

    override fun dismissShipweLoading() {
        super.dismissShipweLoading()
        binding.checkNumberRefreshView.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        eventRemark = "${getProductName()} Verification Page"
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_VERIFICATION_SMS_START, eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_VERIFICATION_SMS_END, eventRemark)
        if (timeThread != null) {
            timeThread!!.stopThread()
            timeThread = null
        }
        if (smsBroadcastReceiver != null){
            unregisterReceiver(smsBroadcastReceiver)
        }
    }
}